﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;

public partial class News : System.Web.UI.Page
{
    protected CategoryItem catItem;
    private int iTotalPages = 0;
    private int iPageSize = 6;
    public int CurrentPage = 1;
    protected string sCategoryName;

    protected void Page_Load(object sender, EventArgs e)
    {
        GetParameters();
        if(!IsPostBack)
            GetNewsData();

        
    }

    #region Get data from DB
    private void GetNewsData()
    {
        Dal.arParams.Clear();
        Dal.arParams.Add(catItem.catId);//CatID
        Dal.arParams.Add(CurrentPage);//Current Page
        Dal.arParams.Add(iPageSize);//PageSize
        DataTable DT = Dal.ExecuteDBsp("usp_GetNewsByCategoryWPaging", Dal.arParams);
        if (DT != null)
        {
            if (DT.Rows.Count > 0)
            {
                iTotalPages = (int)Math.Ceiling((double)Convert.ToInt32(DT.Rows[0]["TotalRows"]) / iPageSize);
                gvNews.DataSource = DT;
                gvNews.DataBind();

                if(iTotalPages>1)
                    SimplePager();
            }
        }
    }

    public void SimplePager()
    {
        if (CurrentPage < 0) CurrentPage = 1;
        if (iTotalPages < 0) iTotalPages = 0;

        var pager = new PagerBuilder(catItem.cPageName);

        if (CurrentPage > 1)
        {
            pager.AddPage("&lt;&lt;", 1);
            pager.AddPage("&lt;", CurrentPage - 1);
        }

        var start = Math.Max(CurrentPage - 2, 1);
        var end = Math.Min(iTotalPages, CurrentPage + 2);

        for (var i = start; i <= end; i++)
        {
            if (i == CurrentPage)
                pager.AddPage(i.ToString(), i, "font-weight: bold; color: #0b61a4;");
            else
                pager.AddPage(i.ToString(), i);
        }

        if (CurrentPage < iTotalPages)
        {
            pager.AddPage("&gt;", CurrentPage + 1);
            pager.AddPage("&gt;&gt;", iTotalPages);
        }

        nav6.InnerHtml+= pager.ToString();
    }

    #region NotInUSE
    //private void GetData()
    //{
    //    ObjectDataSource ods = new ObjectDataSource();
    //    ods.ID = "ods" + 1;
    //    ods.EnablePaging =true; //the paging of ODS depends on the paging of the GridView
    //    ods.TypeName = "MyTableAdapter"; //be sure to prefix the namespace of your application !!! e.g. MyApp.MyTableAdapter

    //    ods.SelectMethod = "GetData";
    //    ods.SelectCountMethod = "VirtualItemCount";
    //    ods.StartRowIndexParameterName = "startRow";
    //    ods.MaximumRowsParameterName = "maxRows";
    //    ods.EnableViewState = false;

    //    ods.ObjectCreating += new ObjectDataSourceObjectEventHandler(ods_ObjectCreating);
    //    gvNews.DataSource = ods;
    //    gvNews.DataBind();

    //    //if (ddlPageNumber.Items.Count == 0 || GVTrivias.PageCount != ddlPageNumber.Items.Count)
    //    //{
    //    //    ddlPageNumber.Items.Clear();
    //    // for (int icount = 1; icount < gvNews.PageCount + 1; icount++)
    //    //   {
    //    ////        ListItem li = new ListItem(icount.ToString(), icount.ToString());
    //    ////        ddlPageNumber.Items.Add(li);
    //    //    }
    //    //    lblShowRecords.Text = string.Format(" {0} ", GVTrivias.PageCount);
    //    //}

    //}

    //private void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    //{
    //    //calling a "parametered" constructor of my own TableAdapter and passing it to the ObjectInstance property 
    //    Dal.arParams.Clear();
    //    Dal.arParams.Add(catItem.catId);//CatID
    //    Dal.arParams.Add(CurrentPage);//Current Page
    //    Dal.arParams.Add(1);//PageSize
    //    DataSet DS = Dal.ExecuteDBspDS("usp_GetNewsByCategoryWPaging", Dal.arParams);

    //    if (DS != null)
    //    {
    //        if (DS.Tables.Count > 0)
    //        {
    //            MyTableAdapter tAdapter = new MyTableAdapter(DS.Tables[0]);
    //            e.ObjectInstance = tAdapter;
    //        }

    //        //and that'all there's to it !!
    //    }
    //}
    #endregion
    #endregion

    private void GetParameters()
    {
        //string sSite = this.Page.Request.Url.Segments[2].Replace("/", "").ToLower();

        CurrentPage=Convert.ToInt32((Request.Params["page"]==string.Empty)?"1":Request.Params["page"]);
        string sFilename=Request.Params["category"];

        catItem = Category.ItemByPageName(sFilename);
        if (catItem != null)
        {
            Page.Title = catItem.cTitle;
            sCategoryName = catItem.cTitle;
            HtmlMeta meta = new HtmlMeta();
            meta.Name = "keywords";
            meta.Content = PageHeaderData.GetPageKeywordsByType((NewsType)catItem.catId);
            this.Header.Controls.Add(meta);

            switch (sFilename)
            {
                case "news":
                    sCategoryName = "Новости медицины Израиля";
                    ucHeader1.index = "2";
                    divTitle.Attributes.Add("class", "title1");
                    CatName.InnerText = "Последние новости медицины Израиля";
                    break;
                case "popularnews":
                    sCategoryName = "Популярные статьи о медицине Израиля";
                    ucHeader1.index = "3";
                    divTitle.Attributes.Add("class", "title2");
                    CatName.InnerText = "Популярные статьи о медицине Израиля";
                    break;

                case "tourism":
                    ucHeader1.index = "6";
                    divTitle.Attributes.Add("class", "title8");
                    CatName.InnerText = "Статьи о медицинском туризме";
                    break;
            }
        }
    }
}

public class PagerBuilder
{
    private class PagerLink
    {
        public string Title { get; set; }
        public int PageNo { get; set; }
        public string Class { get; set; }
    }

    private readonly string _urlTemplate;
    private readonly List<PagerLink> _pagerLinks =
            new List<PagerLink>();

    public PagerBuilder(string urlTemplate)
    {
        _urlTemplate = urlTemplate;
    }

    public string PagerClass { get; set; }

    public void AddPage(string title, int pageNo)
    {
        AddPage(title, pageNo, string.Empty);
    }

    public void AddPage(string title, int pageNo,
                        string itemClass)
    {
        var link = new PagerLink
        {
            PageNo = pageNo,
            Title = title,
            Class = itemClass
        };
        _pagerLinks.Add(link);
    }

    public override string ToString()
    {
        var builder = new StringBuilder();
       
        foreach (var link in _pagerLinks)
        {
            builder.Append("<li>");
            builder.Append("<a");
            if (link.Class != string.Empty)
            {
                builder.AppendFormat(" style=\"{0}\"",link.Class);
            }
            builder.Append(" href=\"");
            builder.AppendFormat("{0}-{1}.aspx",_urlTemplate, link.PageNo);
            builder.Append("\">");
            builder.Append(link.Title);
            builder.Append("</a>");
            builder.Append("</li>");
        }
        return builder.ToString();
    }
}


